/**
Copyright 2008
Contact tushar.kapila@gmail.com http://sel2in.com
*/
// sel2in.img.dogspa.ImgAdd
package br.com.gerador.util;

import java.awt.color.*;
import java.util.*;
import java.io.*;
import java.awt.*;
import java.awt.image.*;
import java.awt.image.*;

import javax.imageio.*;
import javax.imageio.stream.*;

public class ColorHelper{


	public static Color parseColor(String s, Color defClr){
		if(s==null || s.length() < 3)return null;
		if(s.charAt(0) == '#'){
			return parseHashHexa(s, defClr);
		}
		StringTokenizer st = new StringTokenizer(s, " ,()");
		String typ = "rgb";
		if(st.hasMoreTokens()) typ = st.nextToken();
		int r = 0, g = 0, b = 0 , a = 255;
		Color c = defClr;
		try{


			if(st.hasMoreTokens()){
				s = st.nextToken();
				if(s.endsWith("%")){///**/""
					s = s.substring(0, s.length() -1);
					r = (int)(Integer.parseInt(s) * 255 / 100);
				}else{
					r = Integer.parseInt(s);
				}

				if(st.hasMoreTokens()){
					s = st.nextToken();
					if(s.endsWith("%")){
						s = s.substring(0, s.length() -1);
						g = (int)(Integer.parseInt(s) * 255 / 100);
					}else{
						g = Integer.parseInt(s);
					}
					if(st.hasMoreTokens()){
						s = st.nextToken();
						if(s.endsWith("%")){
							s = s.substring(0, s.length() -1);
							b = (int)(Integer.parseInt(s) * 255 / 100);
						}else{
							b = Integer.parseInt(s);
						}
						if(st.hasMoreTokens()){
							s = st.nextToken();
							if(s.endsWith("%")){
								s = s.substring(0, s.length() -1);
								a = (int)(Integer.parseInt(s) * 255 / 100);
							}else{
								a = Integer.parseInt(s);
							}
						}
					}
				}
			}

			c = new Color(r, g, b, a);
		}catch(Throwable e){
			e.printStackTrace();
		}
		return c;
	}

	public static Color parseHashHexa(String s, Color defClr){
		int r = 0, g = 0, b = 0 , a = 255;
		Color c = defClr;
		try{
			r = Integer.parseInt(s.substring(1,3), 16);
			g = Integer.parseInt(s.substring(3,5), 16);
			b = Integer.parseInt(s.substring(5,7), 16);
			if(s.length() > 7)a = Integer.parseInt(s.substring(7, 9), 16);
			c = new Color(r, g, b, a);
		}catch(Throwable e){
			e.printStackTrace();
		}
		return c;
	}
}